const router = require('koa-router')()
const { query } = require("../db")
const { URL } = require("url");
const path = require("path");
const fs = require("fs");
router.prefix('/occult');

//奇闻异事页
router.get('/', async (ctx, next) => {
    let sql = "select * from occult";
    let results = await query(sql, []);
    // console.log(results)
    ctx.res.end(JSON.stringify(results));
})

//异事详情页
router.get("/detail", async (ctx, next) => {
    let sql = "select * from occult where id='" + ctx.request.query.id + "'";
    let results = await query(sql, []);
    ctx.res.end(JSON.stringify(results));
})

//发起搜索请求
router.get("/search", async (ctx, next) => {
    console.log(ctx.request.query.info)
    let sql = `select * from occult where title like '%${ctx.request.query.info}%'`;
    let results = await query(sql, []);
    ctx.res.end(JSON.stringify(results));
})

//从服务端获取图片响应到页面
router.get("/:id", async (ctx, next) => {
    let urlObj = new URL(ctx.req.url, "http://localhost:3000/")
    let name = urlObj.pathname.split("/");
    let filePath = path.join("./public/images/images/" + name[2]);
    let fileContent = fs.readFileSync(filePath);
    ctx.res.writeHead(200, { "Content-Type": "image/png" });
    ctx.res.end(fileContent);
})


//该用户是否喜欢此页面
router.post('/like',async (ctx,next)=>{
    
    console.log(ctx.request.body)
    let sql = "select * from like_occult where occult_id='" + ctx.request.body.occult_id + "' and user_id='"+ ctx.request.body.user_id+"'";
    let results = await query(sql, []);
    ctx.res.end(JSON.stringify(results));

})

//该用户是否收藏此页面
router.post('/collect',async (ctx,next)=>{
    
    console.log(ctx.request.body)
    let sql = "select * from collect where occult_id='" + ctx.request.body.occult_id + "' and user_id='"+ ctx.request.body.user_id+"'";
    let results = await query(sql, []);
    ctx.res.end(JSON.stringify(results));

})


module.exports = router
